<?php

namespace iflow\swoole\implement\Server\Rpc;

use iflow\swoole\abstracts\ServicesAbstract;
use iflow\swoole\implement\Server\Rpc\Cluster\Consumer;
use iflow\swoole\implement\Server\Rpc\Events\Event;
use iflow\swoole\implement\Server\WebSocket\Service as WbService;
use Swoole\Http\Server;

class Service extends WbService {

    public Consumer $consumer;

    protected Event $RpcEvent;

    protected array $event = [
        'connect' => 'onConnect',
        'receive' => 'onReceive',
        'close' => 'onClose',
        'packet' => 'onPacket',
    ];

    protected ?object $defaultRpcServer = null;

    public function start() {
        $this->RpcEvent = new Event($this);

        $this -> checkWebSocketEnable();

        $this->consumer = new Consumer($this->config -> all());
        parent::start(); // TODO: Change the autogenerated stub
    }

    protected function createServiceAfter(): void {
        parent::createServiceAfter(); // TODO: Change the autogenerated stub
        $this->defaultRpcServer = $this->getListenerServer($this->config -> get('listener_default_name') ?: 'rpc_server');

        $this ->addEventValues($this->event, $this->RpcEvent, $this->defaultRpcServer);
    }


    protected function checkWebSocketEnable(): ServicesAbstract {
        $this->isWebSocket = $this->config -> get('websocket@enable', false);
        return $this;
    }

    protected function getSwooleServiceClass(): string {
        return !$this->isWebSocket ? Server::class : \Swoole\WebSocket\Server::class;
    }

}